import { BaseStrategy } from '../BaseStrategy.js';
import { delay, ensurePageOpen } from '../../utils.js';
import { wuliu_rule } from '../../rules/wuliu.js';
import fs from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { platformConfig } from '../../config/index.js';
import { logInfo, logWarn, logError } from '../../logger.js';
import { closePopups } from '../../utils.js';
import statisticsService from '../../services/statistics.js';

const __filename = fileURLToPath(import.meta.url);

export class DouyinStrategy extends BaseStrategy {
  constructor(context) {
    super(context, platformConfig.douyin);
  }

  async processRefunds(accountKey, shopName = '') {
    logInfo(`[DouyinAutomation] 开始处理${shopName || '未知店铺'}的抖音退款订单`);
    let refundRecords = [];
    try {
      const page = await ensurePageOpen(this.context, this.baseUrl + '/ffa/maftersale/aftersale/list');
      this.pageLoad(page);
      await page.waitForTimeout(5000);
      await closePopups(page);
      await page.getByText('退货待商家收货').click().catch(() => { logWarn(`[DouyinAutomation] ${shopName || '未知店铺'}未找到退货待商家收货按钮`); });
      await page.waitForTimeout(5000);
      let countEl = await page.locator('.auxo-pagination-total-text').textContent();
      let count = parseInt(countEl.match(/\d+/)[0]);
      logInfo(`[DouyinAutomation] ${shopName || '未知店铺'}退款订单总数: ${count}`);
      while (count > 0) {
        await page.locator('#orderAppContainer').getByRole('button', { name: '查询' }).click();
        await page.waitForTimeout(5000);
        const next = await this.processRefundItems(page, refundRecords, shopName);
        countEl = await page.locator('.auxo-pagination-total-text').textContent();
        count = parseInt(countEl.match(/\d+/)[0]);
        logInfo(`[DouyinAutomation] ${shopName || '未知店铺'}剩余订单数: ${count}`);
        if (!next) break;
      }
      // 保存所有退款成功数据
      if (accountKey && refundRecords.length > 0) {
        statisticsService.saveRefundRecord(accountKey, refundRecords);
      }
      logInfo(`[DouyinAutomation] ${shopName || '未知店铺'}退款任务执行完成`);
    } catch (error) {
      logError(`[DouyinAutomation] ${shopName || '未知店铺'}退款任务异常: ${error.stack || error}`);
    }
  }

  async processRefundItems(page, refundRecords = [], shopName = '') {
    logInfo(`[DouyinAutomation] ${shopName || '未知店铺'}开始处理退款订单列表`);
    let refundCount = 0;
    const elements = await page.locator('.auxo-table-tbody').locator('tr[data-row-key*="child"]:visible').all();
    logInfo(`[DouyinAutomation] ${shopName || '未知店铺'}elements数量: ${elements.length}`);
    for (const ele of elements) {
      const tuihuo = await ele.locator('.auxo-table-cell').filter({ hasText: '买家退货' })
        .locator('div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > span:nth-child(1)').textContent().catch(() => { logWarn(`[DouyinAutomation] ${shopName || '未知店铺'}获取买家退货状态失败`); });
      logInfo(`[DouyinAutomation] ${shopName || '未知店铺'}退货状态: ${tuihuo}`);
      if (tuihuo === '已发货') {
        const newPagePromise = this.context.waitForEvent('page');
        await ele.getByText('查看详情').click();
        const detailPage = await newPagePromise;
        const itemData = await this.processRefundDetail(detailPage, ele, shopName);
        if (itemData) {
          refundRecords.push(itemData);
          logInfo(`[DouyinAutomation] ${shopName || '未知店铺'}追加数据：${JSON.stringify(itemData)}`);
          refundCount++;
        }
      }
    }
    return refundCount > 5;
  }

  async processRefundDetail(detailPage, item, shopName = '') {
    logInfo(`[DouyinAutomation] ${shopName || '未知店铺'}进入订单详情页`);
    try {
      await detailPage.waitForLoadState('networkidle');
      await detailPage.waitForTimeout(3000);
      // await closePopups(detailPage);
      const thbox = await detailPage.locator('.auxo-tabs').filter({ hasText: '退货物流' });

      await detailPage.locator('.auxo-tabs-tab').filter({ hasText: '退货物流' }).click({ timeout: 1000 }).catch(() => { });


      const plan = await thbox.locator('div[role="tabpanel"]:visible ul.auxo-timeline');

      const state = await plan.locator('li').first().locator('div[class*="itemTitle"]').textContent();

      console.log(state);
      if (state != '已签收') {
        await detailPage.close();
        return false;
      }
      const wuliu = await plan.locator('div[class*="itemDetail"]').allTextContents();
      const result = await wuliu_rule(wuliu);
      if (!result) {
        // 已签收但未命中规则，发送通知
        const orderId = await detailPage.locator('div[class*="item-wrapper"]').filter({ hasText: '订单编号' }).locator('span').first().textContent();
        const refundId = await detailPage.locator('div[class*="item-wrapper"]').filter({ hasText: '售后编号' }).locator('span').first().textContent();
        logInfo(`[DouyinAutomation] ${shopName || '未知店铺'}订单已签收，但未命中签收规则,订单ID：${orderId},退款ID：${refundId}`);
        this.sendNotification(shopName, orderId, refundId);
        await detailPage.close();
        return false;
      }

      //add remark
      let addbtn = null;
      try {
        addbtn = await detailPage.getByText('添加', { timeout: 1000 });
      } catch (error) {
        addbtn = await detailPage.getByText('修改', { timeout: 1000 });
      }

      await addbtn.click();

      await detailPage.waitForTimeout(500);

      await detailPage.getByText('售后备注').click();

      await detailPage.waitForTimeout(500);

      const textboxes = detailPage.getByPlaceholder('请输入备注信息');
      const count = await textboxes.count();
      for (let i = 0; i < count; i++) {
        const textbox = textboxes.nth(i);
        if (await textbox.isVisible()) {
          await textbox.fill('bot');
          break;
        }
      }

      await detailPage.waitForTimeout(500);
      await detailPage.getByText('确定').click();

      await detailPage.waitForTimeout(500);
      await detailPage.getByText('已收到货，退款').click();

      await detailPage.waitForTimeout(3500);
      await detailPage.locator('.auxo-modal-body').getByRole('button', { name: '确认' }).click();

      await detailPage.waitForLoadState('networkidle').catch(() => { });
      await detailPage.waitForTimeout(2500);

      //登记信息

      const itemInfo = {
        '订单编号': await detailPage.locator('div[class*="item-wrapper"]').filter({ hasText: '订单编号' }).locator('span').first().textContent(),
        '售后编号': await detailPage.locator('div[class*="item-wrapper"]').filter({ hasText: '售后编号' }).locator('span').first().textContent(),
        '售后时间': new Date().toLocaleString(),
      };

      logInfo('[DouyinAutomation] 完成订单详情处理');
      await detailPage.close();

      return itemInfo;
    } catch (err) {
      logError(`[DouyinAutomation] 订单详情处理异常: ${err.stack || err}`);
      await detailPage.close();
      return false;
    }
  }

  async getShipmentInfo(shopName) {
    const page = await ensurePageOpen(this.context, this.baseUrl + '/ffa/logistics/parcelCenter');

    this.pageLoad(page);
    await page.waitForTimeout(3000);

    const lsjjcs = await page.locator('div[data-kora="发货包裹V2-揽收即将超时-指标卡片"]>div').nth(1).textContent()
      .catch(() => { });
    const lscs = await page.locator('div[data-kora="发货包裹V2-揽收已超时24h-指标卡片"]>div').nth(1).textContent()
      .catch(() => { });
    const fycs = await page.locator('div[data-kora="发货包裹V2-发运超时-指标卡片"]>div').nth(1).textContent()
      .catch(() => { });

    return {
      '店铺名称': shopName || '抖音',
      '揽收即将超时': lsjjcs,
      '揽收已超时': lscs,
      '发运超时': fycs
    };
  }

  async getExchangePendingCount() {
    const page = await ensurePageOpen(this.context, this.baseUrl + '/ffa/maftersale/aftersale/list');
    await page.waitForTimeout(3000);
    await closePopups(page);

    const countEl = await page.locator('div').filter({ hasText: /^换货待商家收货\/发货/ }).locator('span').nth(2);
    let count = 0;
    try {
      count = parseInt(await countEl.textContent());
    } catch (e) {
      logWarn('[DouyinAutomation] 获取换货待处理订单数失败');
    }
    logInfo(`[DouyinAutomation] 换货待处理订单数: ${count}`);
    return count;
  }

  async test() {
    const page = await ensurePageOpen(this.context, this.baseUrl + '/ffa/maftersale/aftersale/list');
    this.pageLoad(page);
    await page.pause();
  }
}